package models

import (
	"errmsg"
	"fmt"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"time"
	"tools"
)

type UseMode struct {
	Id         string          `orm:"column(id);pk" json:"id" form:"id"`
	UserId     string          `orm:"column(user_id)" json:"user_id" form:"user_id"`
	Name       string          `orm:"column(name)" json:"name" form:"name"`
	Trigger    int             `orm:"column(trigger)" json:"trigger" form:"trigger"`
	IsActivate int             `orm:"column(is_activate)" json:"is_activate" form:"is_activate"`
	StartTime  string          `orm:"column(start_time)" json:"start_time" form:"start_time"`
	EndTime    string          `orm:"column(end_time)" json:"end_time" form:"end_time"`
	IsPush     int             `orm:"column(is_push)" json:"is_push" form:"is_push"`
	Wkocc      string          `orm:"column(wkocc)" json:"wkocc" form:"wkocc"`
	IsShare    int             `orm:"column(is_share)" json:"is_share" form:"is_share"`
	IsOriginal int             `orm:"column(is_original)" json:"is_original" form:"is_original"`
	CreateTime int64           `orm:"column(create_time)" json:"create_time" form:"create_time"`
	Sort       int             `orm:"column(sort)" json:"sort" form:"sort"`
	MarketId   int             `orm:"column(market_id)" json:"market_id" form:"market_id"`
	Task       []*UseModeTasks `orm:"-" json:"task"`
}

const (
	UM_MANUAL = 1 // 手动
	UM_TIMING = 2 // 定时
)

func init() {
	orm.RegisterModel(new(UseMode))
}

func (m *UseMode) TableName() string {
	return "use_mode"
}

// 获取手动模式
func GetManualUM() []*UseMode {
	var (
		ls  []*UseMode
		err error
		num int64
	)
	if num, err = orm.NewOrm().QueryTable("use_mode").Filter("is_activate", 1).Filter("trigger", UM_MANUAL).All(&ls); err != nil {
		logs.Error(err)
		return nil
	}
	if num == 0 {
		return nil
	}

	for k, v := range ls {
		ls[k].Task, _ = GetUseModeTaskByUmid(v.Id)
	}

	return ls
}

func GetTimingUM() []*UseMode {

	var (
		t        time.Time
		currTime string
		week     int
		start    int
		end      int
		ls       []*UseMode
		reg      string
		sql      string
		err      error
		num      int64
	)

	t = time.Now()
	currTime = t.Format("15:04")
	week = tools.GetWeekDay()

	start = week;
	end = 6 - week;
	ls = []*UseMode{}

	reg = fmt.Sprintf("([01]{%d}1[01]{%d})|0{7}", start, end);
	sql = "SELECT * FROM `use_mode` WHERE `is_activate` = 1 AND `trigger` = 2 AND `start_time` = ? AND `wkocc` REGEXP ?"
	if num, err = orm.NewOrm().Raw(sql, currTime, reg).QueryRows(&ls); err != nil {
		logs.Error("GetTimingUM error:", err)
		return nil
	}
	if num == 0 {
		return nil
	}

	for k, v := range ls {
		ls[k].Task, _ = GetUseModeTaskByUmid(v.Id)
	}

	return ls
}

func UpdateUseModeStatus(um *UseMode) error {
	// 数据入库
	if _, err := orm.NewOrm().Update(um); err != nil {
		logs.Error("UpdateUseModeStatus error:", err)
		return errmsg.ErrResponseSystem
	}
	return nil
}
